import React, {memo, useEffect, useState} from 'react';
import {renderRoutes} from "react-router-config";

import "./index.css";
import Header from "../../../components/main-header/Header";
import PageNavigation from "../../../components/pageNavigation/PageNavigation";
import {LOAD_ANALYSIS} from "../../../common/loadType";
import {message} from "antd";
import {useDispatch, useSelector} from "react-redux";
import {saveData} from "../store/actionCreators";
import {calCqMean, calQuantityMean, deepClone, getAnalysisInfo, getContextPath, getExcelData} from "../../../common/utils";
import {saveAnalysisShowLineArr} from "../plate/store/actionCreators";
import request from "../../../services/request";
import {useSaveEndPointSetting} from "../../../common/myHooks";
import {saveExperimentSetting} from "./components/geneExpression/store/actionCreators";

export default memo(function Analysis(props) {
  const navContent = [
    {content: "Quantification", path: "/main/analysis"},
    {content: "Melt Curve", path: "/main/analysis/meltCurve"},
    {content: "Gene Expression", path: "/main/analysis/geneExpression"},
    {content: "Allelic Discrimination", path: "/main/analysis/allelicDiscrimination"},
    {content: "Quality Control", path: "/main/analysis/quanlityControl"},
    {content: "End-Point", path: "/main/analysis/endPoint"}];
  const navContent_CN = [
    {content: "定量分析", path: "/main/analysis"},
    {content: "熔解曲线", path: "/main/analysis/meltCurve"},
    {content: "基因表达", path: "/main/analysis/geneExpression"},
    {content: "等位基因分析", path: "/main/analysis/allelicDiscrimination"},
    {content: "质量控制", path: "/main/analysis/quanlityControl"},
    {content: "终点法", path: "/main/analysis/endPoint"}];
  const dispatch = useDispatch();
  const {data, isCN, analysisShowLineArr, tableSelectedLists, experimentSetting,allelicTableData, endPointSetting, technicalTableData, failureReport, dataAnalysisMethod,tableSelectedListsShort} = useSelector(state => ({
    data: state.dataReducer.data,
    analysisShowLineArr: state.plateReducer.analysisShowLineArr,
    dataAnalysisMethod: state.quantificationReducer.dataAnalysisMethod,  //  分析的方法(3种)
    tableSelectedLists: state.quantificationReducer.tableSelectedLists,//  tableSelected列表,
    technicalTableData: state.geneSettingReducer.technicalTableData, //  Gene Expression表格数据
    allelicTableData: state.allelicReducer.allelicTableData,//  Allelic表格数据
    failureReport: state.quanlityControlReducer.failureReport,
    endPointSetting: state.endPointReducer.endPointSetting,
    isCN: state.languageReducer.isCN,
    experimentSetting: state.geneSettingReducer.experimentSetting
  }));
  const [showExportAside, setShowExportAside] = useState(false);
  const [excelTitle, setExcelTitle] = useState([
    {name: "Quantification Results", selected: true},
    {name: "Melt Data", selected: false},
    {name: "RFU spreadsheet", selected: false},
    {name: "RFU melt", selected: false},
    {name: "Gene Expression Data", selected: false},
    {name: "Allelic Discrimination", selected: false},
    {name: "QC Summary", selected: false},
    {name: "Determination Data", selected: false}
  ]);
  const [exportUrl, setExportUrl] = useState("");
  const saveEndPointSetting = useSaveEndPointSetting();
  let cloneExcelTitle = [];
  let cloneData = {};

  useEffect(() => {
    if (!exportUrl) {
      return;
    }
    let iframe = document.createElement("iframe");
    iframe.src = exportUrl;
    iframe.style.display = "none";
    document.body.appendChild(iframe);
    setTimeout(() => iframe.remove(), 1000);
  }, [exportUrl]);

  //  选择导出的内容
  function selectExportItem(indey) {
    cloneExcelTitle = deepClone(excelTitle, cloneExcelTitle);
    cloneExcelTitle[indey].selected = !cloneExcelTitle[indey].selected;
    setExcelTitle(cloneExcelTitle);
  }

  //  导出Excel
  function exportExcel() {
    setExportUrl("");
    let excelData = {
      experimentName: data.experimentName,
      userName: data.userName,
      sheets: []
    };
    excelTitle.forEach(
      (item, index) => item.selected &&
      excelData.sheets.push(getExcelData(index, analysisShowLineArr, technicalTableData, allelicTableData, failureReport, endPointSetting, data, dataAnalysisMethod)));
    console.log(analysisShowLineArr);
    message.info("Please wait a moment");
    request({
      url: 'downloadAction/downloadExcel',
      data: excelData,
      method: 'post'
    }).then(() => {
      setExportUrl(getContextPath() + "/downloadAction/downloadExcelUrl");
    }).catch(err => message.error(err));
    setShowExportAside(false);
  }

  //  重新分析实验
 /* function analysisExperiment() {
    cloneData = deepClone(data, cloneData);
    //后台请求计算起始循环数
    request({
      url: 'analysis/calStartEndCycle',
      data: {...cloneData},
      method: 'post'
    })
      .then(r => {
        switch (r.code) {
          case 200:
            debugger
            let w = r.data
            request({
              url: 'analysis/calAll',
              data: {...r.data},
              method: 'post'
            })
              .then(res => {
                switch (res.code) {
                  case 200:
                    let t = res.data
                    //  保存data
                    calCqMean(res.data);
                    calQuantityMean(res.data);
                    dispatch(saveData(res.data));
                    dispatch(saveAnalysisShowLineArr(getAnalysisInfo(res.data).analysisShowLineArr)); //  保存可以画线的数据(只有target和sample同时选择后才能画线)
                    saveEndPointSetting(res.data);
                    break;
                  case 500:
                    message.error(res.message);
                    break;
                  default:
                    message.error("error");
                    // TODO: 排查错误
                    console.log(res);
                }
              })
              .catch(err => message.error(err));
            break;
          case 500:
            message.error(r.message);
            break;
          default:
            message.error("error");
            // TODO: 排查错误r
            console.log(r);
        }
      })
      .catch(err => message.error(err));
  /!*  request({
      url: 'analysis/calAll',
      data: data,
      method: 'post'
    })
      .then(res => {
        switch (res.code) {
          case 200:
            //  保存data
            calCqMean(res.data);
            calQuantityMean(res.data);
            dispatch(saveData(res.data));
            dispatch(saveAnalysisShowLineArr(getAnalysisInfo(res.data).analysisShowLineArr)); //  保存可以画线的数据(只有target和sample同时选择后才能画线)
            saveEndPointSetting(res.data);
            break;
          case 500:
            message.error(res.message);
            break;
          default:
            message.error("error");
            // TODO: 排查错误
            console.log(res);
        }
      })
      .catch(err => message.error(err));*!/
  }*/
  //  重新分析实验
  function analysisExperiment() {
    request({
      url: 'analysis/calAll',
      data: data,
      method: 'post'
    })
      .then(res => {
        switch (res.code) {
          case 200:
            //  保存data
            console.log(data);
            calCqMean(res.data);
            calQuantityMean(res.data);
            dispatch(saveData(res.data));
            dispatch(saveAnalysisShowLineArr(getAnalysisInfo(res.data).analysisShowLineArr)); //  保存可以画线的数据(只有target和sample同时选择后才能画线)
            saveEndPointSetting(res.data);
            let targets = [];
            targets = deepClone(experimentSetting.targets, targets);
            targets.forEach((item, index) => {
              let t = res.data.targets.find(it => it.name === item.name);
              targets[index].e = t.e;
            });
            dispatch(saveExperimentSetting({...experimentSetting, targets}));
            break;
          case 500:
            message.error(res.message);
            break;
          default:
            message.error("error");
            // TODO: 排查错误
            console.log(res);
        }
      })
      .catch(err => message.error(err));
  }

  return (
    <div>
      <Header name={isCN ? "数据分析" : "Analysis"}
              imgPosition="-200px"
              isLoad={true}
              isSave={true}
              isExport={true}
              isAnalysis={true}
              analysisAction={analysisExperiment}
              loadType={LOAD_ANALYSIS}
              setShowExportAside={setShowExportAside}
      />
      <section className="mainSection">
        <PageNavigation navContent={isCN ? navContent_CN : navContent}/>
        {renderRoutes(props.route.routes)}
      </section>
      {
        showExportAside
          ? <aside className="exportAside asideBoxHeader">
            <header>
              <div>
                <p>Export Excel</p>
                <p onClick={() => setShowExportAside(false)}/>
              </div>
              <hr/>
            </header>
            <section>
              <ul>
                {
                  excelTitle.map((item, index) => (
                    <li key={item.name}>
                      <div className={item.selected ? "selectedStyle" : null}
                           onClick={() => selectExportItem(index)}
                      />
                      <div>{item.name}</div>
                    </li>
                  ))
                }
              </ul>
            </section>
            <footer>
              <hr/>
              <div onClick={exportExcel}>OK</div>
            </footer>
          </aside>
          : null
      }
    </div>
  );
});
